package org.dtrd.modules.record.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.system.vo.DictModel;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.record.entity.bean.SportBean;
import org.dtrd.modules.record.entity.request.TimePeriodRequest;
import org.dtrd.modules.record.service.ISportRecordService;
import org.dtrd.modules.system.mapper.SysDictMapper;
import org.dtrd.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;
import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_SAVE_OR_UPDATE;

/**
 * @Author QR
 * @Date 2021/11/3 10:31 AM
 */
@Api(tags = "运动打卡")
@RestController
@RequestMapping("/101/03")
public class SportRecordController extends BaseController {

    @Autowired
    private ISportRecordService sportRecordService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private ISysDictService sysDictService;
    public static final String SPORT = "sport";

    @ApiOperation("添加或修改运动记录")
    @PostMapping("/1010301")
    private Result<?> saveOrUpdateSportRecord(@RequestBody SportBean sportBean) {
        if (isIntParamInvalid(sportBean.getPatientId())
                || StrUtil.isBlank(sportBean.getRecordTime())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        boolean result = sportRecordService.saveOrUpdateSportRecord(sportBean);
        String logContent = String.format("添加或修改运动记录，患者id：%d", sportBean.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("分页查询运动记录列表")
    @PostMapping("/1010302")
    private Result<?> getSportRecordList(@RequestBody TimePeriodRequest request) {
        if (isIntParamInvalid(request.getPatientId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        int type = getIntParam(request.getType(), 1);
        if (type == 1 || type == 3) {
            Integer page = getIntParam(request.getPage(), 1);
            Integer pageSize = getIntParam(request.getPageSize(), 20);
            String startDate = null;
            String endDate = null;
            String[] timePeriod = handleTimePeriod(request);
            if (timePeriod != null) {
                startDate = timePeriod[0];
                endDate = timePeriod[1];
            }
            if (startDate == null || endDate == null) {
                return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
            }
            Integer patientId = request.getPatientId();
            int count = sportRecordService.getSportRecordCountByDateRange(patientId, startDate, endDate);
            JSONObject result = new JSONObject();
            if (count > 0) {
                List<SportBean> list = sportRecordService.getSportRecordListByDateRange(patientId, startDate, endDate, page, pageSize);
                List<DictModel> sportList = sysDictService.queryDictItemsByCode(SPORT);
                list.stream().filter(item -> item.getSportRecordSteptype() != null).forEach(item -> {
                    Optional<DictModel> first = sportList.stream().filter(sport -> Objects.equals(sport.getValue(), item.getSportRecordSteptype())).findFirst();
                    first.ifPresent(dictModel -> item.setSportRecordStepTypeName(dictModel.getText()));
                });
                result.put("recordList", list);
                result.put("totalPage", count <= pageSize || pageSize <= 0 ? 1 : setTotalPage(pageSize, count));
                result.put("count", count);
            } else {
                result.put("recordList", Collections.EMPTY_LIST);
                result.put("totalPage", 1);
                result.put("count", 0);
            }
            String logContent = String.format("分页查询运动记录列表，患者id：%d", request.getPatientId());
            baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
            return Result.OK(result);
        }
        return error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }
}
